package org.hhy.cloud.crawl.controller;

import org.hhy.cloud.crawl.entity.Job;
import org.hhy.cloud.crawl.entity.TemplateField;
import org.hhy.cloud.crawl.entity.TemplatePage;
import org.hhy.cloud.crawl.service.JobService;
import org.hhy.cloud.crawl.service.TemplateFieldService;
import org.hhy.cloud.crawl.service.TemplatePageService;
import org.hhy.cloud.crawl.vo.JobVO;
import org.hhy.cloud.crawl.vo.TemplateFieldVO;
import org.hhy.cloud.crawl.vo.TemplatePageVO;
import org.lht.boot.lang.util.R;
import org.lht.boot.web.api.param.QueryParam;
import org.lht.boot.web.api.param.Term;
import org.lht.boot.web.api.param.TermEnum;
import org.lht.boot.web.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: 爬虫配置
 *
 * @Author lht
 * @Date 2020/10/31 12:05 PM
 **/
@RestController
@RequestMapping("/job")
public class JobController  extends AbstractController<Job,String, JobVO, JobService> {

    @Autowired
    private TemplatePageService pageService;

    @Autowired
    private TemplateFieldService fieldService;

    /**
     * 添加爬虫信息
     * @param spiderJob 爬虫信息
     * @return
     */
    @PostMapping("/addSpiderJob")
    public R addSpiderJob(@RequestBody JobVO spiderJob){
        //添加爬虫任务信息
        Job job = voToEntity(spiderJob);
        String jobId = service.insert(job);
        if(StringUtils.isEmpty(jobId)){
            return R.error("爬虫信息添加失败");
        }

        //添加模板页信息
        TemplatePageVO pagesVo = spiderJob.getPages();
        if(pagesVo != null) {
            TemplatePage pages = pagesVo.voToEntity();
            pages.setJobId(jobId);
            String pageId = pageService.insert(pages);
            if(StringUtils.isEmpty(pageId)){
                return R.error("模板页信息添加失败");
            }
            //添加模板页字段信息
            List<TemplateFieldVO> fieldVos = spiderJob.getPages().getFields();
            if(fieldVos != null && !fieldVos.isEmpty()) {
                List<TemplateField> fields = fieldVos.stream().map(TemplateFieldVO::voToEntity)
                        .collect(Collectors.toList());
                fields.forEach(templateField -> templateField.setPageId(pageId));
                fieldService.insert(fields);
            }
        }
        return R.ok();
    }

    /**
     * 编辑爬虫信息
     * @param spiderJob 爬虫信息
     * @return
     */
    @PatchMapping("/patchSpiderJob")
    public R patchSpiderJob(@RequestBody JobVO spiderJob){
        //添加爬虫任务信息
        Job job = voToEntity(spiderJob);
        service.patch(job);

        //添加模板页信息
        TemplatePageVO pagesVo = spiderJob.getPages();
        if(pagesVo != null) {
            TemplatePage pages = pagesVo.voToEntity();
            pageService.patch(pages);
            //添加模板页字段信息
            List<TemplateFieldVO> fieldVos = spiderJob.getPages().getFields();
            if(fieldVos != null && !fieldVos.isEmpty()) {
                List<TemplateField> fields = fieldVos.stream().map(TemplateFieldVO::voToEntity)
                        .collect(Collectors.toList());
                //比对前端与数据库中的模板页字段，找出新增或删除的模板页字段，在数据库中新增或删除对应模板页字段
                List<TemplateField> originalFields = fieldService.select(QueryParam.build(Term.build("pageId", pages.getId())));
                //删除情况
                if(originalFields != null && !originalFields.isEmpty()){
                    //库表中模板页字段信息
                    List<String> originalFieldIds = originalFields.stream().map(TemplateField::getId).collect(Collectors.toList());
                    //接收的前端模板页字段信息与之求差集，得出被删除的模板页字段信息
                    originalFieldIds.removeAll(
                            fields.stream().filter(field-> field.getId() != null)
                                    .map(TemplateField::getId)
                                    .collect(Collectors.toList())
                    );
                    if(!originalFieldIds.isEmpty()){
                        int deleteResult = fieldService.delete(QueryParam.build(Term.build("id", TermEnum.in, originalFieldIds)));
                        if(deleteResult < 0){
                            R.error("模板页字段信息删除失败,关联模板页id=" + pages.getId());
                        }
                    }
                }
                //新增情况
                List<TemplateField> addedFields = fields.stream().filter(field -> field.getId() == null || "".equals(field.getId()))
                        .collect(Collectors.toList());
                if(!addedFields.isEmpty()){
                    addedFields.forEach(field -> field.setPageId(pages.getId()));
                    fieldService.insert(addedFields);
                }
                fieldService.patch(fields);
            }else {
                //接收的前端模板页字段信息为空，直接删除数据库中对应模板页关联的模板页字段信息
                int deleteResult = fieldService.delete(QueryParam.build(Term.build("pageId", pages.getId())));
                if(deleteResult < 0){
                    R.error("模板页字段信息删除失败,关联模板页id=" + pages.getId());
                }
            }
        }
        return R.ok();
    }


    @DeleteMapping("/deleteSpiderJob/{jobId}")
    public R deleteSpiderJob(@PathVariable String jobId){
        if(StringUtils.isEmpty(jobId)) {
            return R.error("爬虫Id为空不合法！");
        }
        int deleteResult;
        List<TemplatePage> pages = pageService.select(QueryParam.build(Term.build("jobId", jobId)));
        if(pages != null && !pages.isEmpty()) {
            //删除模板页级联的模板页字段信息
            List<String> pageIds = pages.stream().map(TemplatePage::getId).collect(Collectors.toList());
            deleteResult = fieldService.delete(QueryParam.build(Term.build("pageId", TermEnum.in, pageIds)));
            if(deleteResult < 0) {
                return R.error("模板页字段信息删除失败,关联模板页id=" + pageIds);
            }
            //删除爬虫任务级联的模板页信息
            deleteResult = pageService.delete(QueryParam.build(Term.build("jobId", jobId)));
            if(deleteResult < 0) {
                return R.error("模板页信息删除失败,关联爬虫id=" + jobId);
            }
        }
        //删除爬虫任务信息
        deleteResult = service.delete(jobId);
        if(deleteResult < 0) {
            return R.error("爬虫删除失败,爬虫id=" + jobId);
        }
        return R.ok();
    }

    @GetMapping("/getSpiderJobDetails/{jobId}")
    public R getSpiderJobDetails(@PathVariable String jobId){
        if(StringUtils.isEmpty(jobId)) {
            return R.error("爬虫Id为空不合法！");
        }
        //查询指定爬虫id的爬虫信息
        Job job = service.get(jobId);
        if(job == null){
            return R.error("该爬虫不存在,爬虫id=" + jobId);
        }
        JobVO jobVO = entityToVo(job);

        //查询指定爬虫id的关联模板页信息
        List<TemplatePage> pages = pageService.select(QueryParam.build(Term.build("jobId", jobId)));
        if(pages != null && !pages.isEmpty()){
            TemplatePageVO templatePageVO = new TemplatePageVO().covertToVO(pages.get(0));
            jobVO.setPages(templatePageVO);

            //查询指定模板页id的关联模板页字段信息
            List<String> pageIds = pages.stream().map(TemplatePage::getId).collect(Collectors.toList());
            List<TemplateField> fields = fieldService.select(QueryParam.build(Term.build("pageId", TermEnum.in, pageIds)));
            if(fields != null && !fields.isEmpty()){
                 List<TemplateFieldVO> fieldVos = fields.stream()
                        .map(templateField -> {
                            TemplateFieldVO templateFieldVO = new TemplateFieldVO().covertToVO(templateField);
                            return templateFieldVO;
                        })
                 .collect(Collectors.toList());
                templatePageVO.setFields(fieldVos);
            }
        }
        return R.ok(jobVO);
    }
}
